//---------------------------------------------
//  Exchange Web Services Mac Widget
// ----------------------------------------------

var currentItemClass = "";

// Sends a GetItem request to EWS.
function getItem(id)
{
    var data = "";
    
    data += "<?xml version='1.0' encoding='utf-8'?>";
    data += "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
    data += "  xmlns:xsd='http://www.w3.org/2001/XMLSchema' ";
    data += "  xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' ";
    data += "  xmlns:t='http://schemas.microsoft.com/exchange/services/2006/types'>";
    data += "  <soap:Body>";
    data += "    <GetItem xmlns='http://schemas.microsoft.com/exchange/services/2006/messages'";
    data += "      xmlns:t='http://schemas.microsoft.com/exchange/services/2006/types'>";
    data += "      <ItemShape>";
    data += "        <t:BaseShape>AllProperties</t:BaseShape>";
    data += "      </ItemShape>";
    data += "      <ItemIds>";
    data += "        <t:ItemId Id='" + id + "'/>";
    data += "      </ItemIds>";
    data += "    </GetItem>";
    data += "  </soap:Body>";
    data += "</soap:Envelope>";
    
    executeEwsRequest(data, readGetItemResponse);
}

// Reads the response to the GetItem request sent in getItem. 
function readGetItemResponse(responseString)
{
	var xmlDoc = createXmlDocument(responseString);
	var findResults = extractSingleItemNodes(xmlDoc);
	
	if (findResults.nodes != null)
	{
		headerContainer.innerHTML = generateFlyoutHeaderHtml(xmlDoc);    
        var frameDocument = document.getElementById("bodyFrame").contentWindow.document;
        
        frameDocument.open();
        frameDocument.write(getItemBody(xmlDoc));
        frameDocument.close();
        
        xmlDoc = null;
	}
}

// Returns true if the specified item class is a message class.
function isMessageClass(itemClass)
{
    switch (itemClass)
    {
        case "t:Message":
        case "t:MeetingMessage":
        case "t:MeetingResponse":
        case "t:MeetingCancellation":
        case "t:MeetingRequest":
            return true;
        default:
            return false;
    }
}

// Generates the flyout header's HTML to display an item's summary information.
function generateFlyoutHeaderHtml(xmlDoc)
{
    var html = "";
    
    var itemsNodes = xmlDoc.getElementsByTagName("Items");
    
    if (itemsNodes.length > 0)
    {
        var headerLines = new Array();
        
        var itemNode = itemsNodes[0].childNodes[0];
        
        // Remember the item's class so we can open it in OWA.
        currentItemClass = getXmlNodeText(itemNode, "ItemClass");

        var titleLine = getXmlNodeText(itemNode, "Subject");
        var subTitleLine;
        
        switch (itemNode.nodeName)
        {
            case "t:Message":
            case "t:MeetingMessage":
            case "t:MeetingResponse":
            case "t:MeetingCancellation":
                var displayName = getXmlNodeText(itemNode, "Name");
                var emailAddress = getXmlNodeText(itemNode, "EmailAddress");
                
                if (displayName != "")
                {
                    subTitleLine = displayName;
                }
                else
                {
                    subTitleLine = emailAddress;
                }

                var dateTimeReceived = convertXsDateTimeToDate(getXmlNodeText(itemNode, "DateTimeReceived"));
                
                headerLines[0] = "<b>Sent</b>: " + dateTimeReceived.toLocaleString();
                headerLines[1] = "<b>To:</b> " + getXmlNodeText(itemNode, "DisplayTo");
                
                var cc = getXmlNodeText(itemNode, "DisplayCc");
                
                if (cc != "")
                {
                    headerLines[2] = "<b>Cc:</b> " + cc;
                }
                    
                break;
            case "t:Task":
                subTitleLine = getTaskStatusDescription(getXmlNodeText(itemNode, "Status")) + 
                    " (" + getXmlNodeText(itemNode, "PercentComplete") + "% complete)";
                    
                headerLines[0] = "<b>Due date:</b> " +
                    convertXsDateTimeToDate(getXmlNodeText(itemNode, "DueDate")).toLocaleDateString();
                headerLines[1] = "<b>Priority:</b> " + getXmlNodeText(itemNode, "Importance");
                    
                break;
            case "t:CalendarItem":
            case "t:MeetingRequest":
                var displayName = getXmlNodeText(itemNode, "Name");
                var emailAddress = getXmlNodeText(itemNode, "EmailAddress");
                
                if (displayName != "")
                {
                    subTitleLine = displayName;
                }
                else
                {
                    subTitleLine = emailAddress;
                }
                
                var startDate = convertXsDateTimeToDate(getXmlNodeText(itemNode, "Start"));
                var endDate = convertXsDateTimeToDate(getXmlNodeText(itemNode, "End"));
                
                var when = formatDateTime(startDate, false, true) + " - " + formatShortCalendarItemDate(endDate, startDate);
                
                headerLines[0] = "<b>Required:</b> " + getXmlNodeText(itemNode, "DisplayTo");
                headerLines[1] = "<b>When:</b> " + when;
                headerLines[2] = "<b>Location:</b> " + getXmlNodeText(itemNode, "Location");
                
                break;
            default:
                headerLines[0] = currentItemClass;
                
                break;
        }
        
        html += "<div class='flyoutHeaderTitleText'>" + titleLine + "</div>";
//		html += "<div class='flyoutCloseButton' onclick='closeFlyout()'><b>x</b></div>"; 
        html += "<div class='flyoutHeaderSubTitleText'>" + subTitleLine + "</div>";
        
        for (i = 0; i < headerLines.length; i++)
        {
            html += "<div class='flyoutHeaderText'>" + headerLines[i] + "</div>";
        }
        
        var id = itemNode.getElementsByTagName("ItemId")(0).getAttribute("Id");
        var changeKey = itemNode.getElementsByTagName("ItemId")(0).getAttribute("ChangeKey");
        
        html += "<div class='clickableLink'>";
        
        if (isMessageClass(itemNode.nodeName))
        {
            var markAsMethodName = "markAsRead";
            var markAsText = "Mark as read";
			var isReadNode = getXmlNodeText(itemNode, "IsRead");
  
            if (isReadNode == "true")
            {
                markAsMethodName = "markAsUnread";
                markAsText = "Mark as unread";
            }
            
            html += "  <span class='flyoutlink' onclick='" + markAsMethodName + "(" + '"' + id + '", "' 
				+ changeKey + '"' + ")' style='border-right: 1px solid Black; padding-right: 4px'>" 
				+ markAsText + "</span>";
			
            html += "  <span class='flyoutlink' onclick='deleteItem(" + '"' + id + '"' +")'>Delete</span>";
        }
        
        if (getOwaUrl() != null)
        {
            html += "  <span class='flyoutlink' onclick='convertEwsIdToOwaId(" + '"' + id + '"' 
				+")' style='border-left: 1px solid Black; padding-left: 4px'>More details...</span>";
        }
        
        html += "</div>";
    }
    
    itemsNodes = null;
    
    return html;
}

// Extracts and returns an item's body from a GetItem response.
function getItemBody(xmlDoc)
{
    var bodyText = "";

	var itemsNodes = xmlDoc.getElementsByTagName("Items");  //selectNodes("//m:Items");    
    if (itemsNodes.length > 0)
    {        
        var itemNode = itemsNodes[0].childNodes[0];
		bodyText = getXmlNodeText(itemNode, "Body");;
    }

    return bodyText;
}

function sendMarkAsRequest(id, changeKey, markAsRead)
{
    var data = "";
    
    data += "<?xml version='1.0' encoding='utf-8'?>";
    data += "<soap:Envelope ";
    data += "  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
    data += "  xmlns:xsd='http://www.w3.org/2001/XMLSchema' ";
    data += "  xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' ";
    data += "  xmlns:t='http://schemas.microsoft.com/exchange/services/2006/types'>";
    data += "  <soap:Body>";
	data += "    <UpdateItem MessageDisposition='SaveOnly' ConflictResolution='AutoResolve'";
    data += "      xmlns='http://schemas.microsoft.com/exchange/services/2006/messages'>";
    data += "      <ItemChanges>";
    data += "        <t:ItemChange>";
    data += "          <t:ItemId Id='" + id + "' ChangeKey='" + changeKey + "'/>";
    data += "          <t:Updates>";
    data += "            <t:SetItemField>";
    data += "              <t:FieldURI FieldURI='message:IsRead'/>";
    data += "              <t:Message>";
    data += "                <t:IsRead>" + markAsRead + "</t:IsRead>";
    data += "              </t:Message>";
    data += "            </t:SetItemField>";
    data += "          </t:Updates>";
    data += "        </t:ItemChange>";
    data += "      </ItemChanges>";
    data += "    </UpdateItem>";
    data += "  </soap:Body>";
    data += "</soap:Envelope>";
  
    executeEwsRequest(data, null);
 
    setIsRefreshNeeded(true);   
    closeFlyout();
	
	refreshTiles();
}

// Marks the item with the specified Id as read.
function markAsRead(id, changeKey)
{
    sendMarkAsRequest(id, changeKey, "true");
}

// Marks the item with the specified Id as not read.
function markAsUnread(id, changeKey)
{
    sendMarkAsRequest(id, changeKey, "false");
}

// Deletes the item with the specified Id.
function deleteItem(id)
{
    var data = "";
    
    data += "<?xml version='1.0' encoding='utf-8'?>";
    data += "<soap:Envelope ";
    data += "  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
    data += "  xmlns:xsd='http://www.w3.org/2001/XMLSchema' ";
    data += "  xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' ";
    data += "  xmlns:t='http://schemas.microsoft.com/exchange/services/2006/types'>";
    data += "  <soap:Body>";
    data += "    <DeleteItem DeleteType='MoveToDeletedItems' xmlns='http://schemas.microsoft.com/exchange/services/2006/messages'>";
    data += "      <ItemIds>";
    data += "        <t:ItemId Id='" + id + "'/>";
    data += "      </ItemIds>";
    data += "    </DeleteItem>";
    data += "  </soap:Body>";
    data += "</soap:Envelope>";
    
    executeEwsRequest(data, null);
    
    setIsRefreshNeeded(true);   
    closeFlyout();
	
	refreshTiles();
}

// Converts an Id in the EWS format into the OWA format.
function convertEwsIdToOwaId(id)
{
    var data = "";
    
    data += "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:t='http://schemas.microsoft.com/exchange/services/2006/types'>";
    data += "  <soap:Header>";
    data += "    <t:RequestServerVersion Version='Exchange2007_SP1'/>";
    data += "  </soap:Header>";
    data += "  <soap:Body>";
    data += "    <ConvertId xmlns='http://schemas.microsoft.com/exchange/services/2006/messages' DestinationFormat='StoreId'>";
    data += "      <SourceIds>";
    data += "        <t:AlternateId Id='" + id + "' Format='EwsLegacyId' Mailbox='dummy@example.com'/>";
    data += "      </SourceIds>";
    data += "    </ConvertId>";
    data += "  </soap:Body>";
    data += "</soap:Envelope>";

    executeEwsRequest(data, readConvertIdResponseAndOpenOwa);
}

// Reads the response to the ConvertId request sent in convertEwsIdToOwaId
// and opens OWA to display the item in its dedicated edit form.
function readConvertIdResponseAndOpenOwa(responseString)
{
	var myOWAID = "";

	var xmlDoc = createXmlDocument(responseString);

	// Get the alternate Id
	var alternateIds = xmlDoc.getElementsByTagName("AlternateId");
	
	if (alternateIds.length > 0)
	{
		// Get the new Id
		var owaId = alternateIds[0].getAttribute("Id");

		// Must convert the "+" to an HTMLEncoding
		while (owaId.indexOf('+') > 0)
		{
			owaId = owaId.replace('+', '%2b');
		}
		
		var owaUrl = getOwaUrl();
		
		if (owaUrl != null)
		{
			widget.openURL(owaUrl + "?ae=Item&a=Read&t=" + currentItemClass + "&id=" + owaId);
		}
		else
		{
			alert("The gadget was unable to determine the Outlook Web Access URL.");
		}
	}
	
	xmlDoc = null;
	
	refreshTiles();
}